<template>
  <div class="todoapp">
    <Header @onkeyup="btn" :arr="list"></Header>
    <Main @delItem="delItem" :list="fliterList"></Main>
    <Footer
      @clearUndone="clearundone"
      @setActive="setActive"
      :arr="list"
      :active="isActive"
    ></Footer>
  </div>
</template>

<script>
import Header from "./components/TODOHeader.vue";
import Main from "./components/TODOMain.vue";
import Footer from "./components/TODOFooter.vue";

export default {
  data() {
    return {
      isActive: "all",
      // all 为全部 undone 为未完成 done 为已完成
      list: JSON.parse(localStorage.getItem("list")) || [],
    };
  },

  // 定义方法
  methods: {
    // 添加
    btn(val) {
      const flag = this.list.some((item) => item.name === val);
      if (flag) return alert("存在");
      this.list.push({
        id: this.list[this.list.length - 1]
          ? this.list[this.list.length - 1].id + 1
          : 100,
        name: val,
        isDone: false,
      });
    },
    // 清空已完成
    clearundone(undone) {
      this.list = undone;
    },
    // 设置高亮
    setActive(active) {
      this.isActive = active;
    },
    // 删除数据
    delItem(id) {
      const index = this.list.findIndex((item) => {
        return item.id === id;
      });
      this.list.splice(index, 1);
    },
  },

  // 组件注册
  components: {
    Header,
    Main,
    Footer,
  },

  // 计算属性
  computed: {
    fliterList() {
      if (this.isActive === "done") {
        return this.list.filter((item) => item.isDone);
      }
      if (this.isActive === "undone") {
        return this.list.filter((item) => !item.isDone);
      }
      return this.list;
    },
  },

  // 监视数据
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("list", JSON.stringify(this.list));
      },
    },
  },

  // 生命周期
  created() {},
};
</script>

<style scoped></style>
